<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <link href="../assets/bootstrap.min.css" rel="stylesheet" />
    <link href="../assets/index.css" rel="stylesheet" />
  </head>
  <style>
    .requireLabel::before {
      content: "*";
      color: #f00;
      display: inline-block;
      margin: 0 5px 0 -10px;
    }
  </style>
  <body>
    <div class="container">
      <form>
        <div class="mb-3">
          <label class="form-label requireLabel" for="room-token">房间号</label>
          <input type="text" class="form-control" id="room-token" required />
        </div>
        <button class="btn btn-primary" id="join-room-btn">加入房间</button>
        <button class="btn btn-primary" disabled id="leave-room-btn">
          退出房间
        </button>
      </form>
    </div>

    <div class="container" id="media-container"></div>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="../assets/bootstrap.bundle.min.js"></script>
    <script src="../assets/qnweb-rtc.js"></script>

    <script>
      const client = QNRTC.createClient();

      const joinRoomBtn = document.getElementById("join-room-btn");
      const leaveRoomBtn = document.getElementById("leave-room-btn");
      const roomTokenInput = document.getElementById("room-token");
      const mediaContainer = document.getElementById("media-container");

      let localTracks = [];

      async function handleUserPublished(userID, tracks) {
        try {
          const { videoTracks, audioTracks } = await client.subscribe(tracks);
          playUserTracks([...videoTracks, ...audioTracks]);
        } catch (e) {
          alert(e.message, "warning");
        }
      }

      function playUserTracks(tracks) {
        for (const track of tracks) {
          if (track.isAudio()) {
            track.play(document.body).catch((e) => {
              alert(e.message, "warning");
            });
          } else {
            const div = document.createElement("div");
            if (track.trackID) div.id = track.trackID;
            mediaContainer.appendChild(div);
            track.play(div).catch((e) => {
              alert(e.message, "warning");
            });
          }
        }
      }

      function handleUserUnPublished(userID, tracks) {
        for (const track of tracks) {
          let div = document.getElementById(track.trackID);
          if (div) div.remove();
        }
      }

      joinRoomBtn.onclick = async (e) => {
        e.preventDefault();
        if (!roomTokenInput.value) return;
        axios
          .get("http://192.168.3.34:29999/wz/rtc/wzRtc/getRoomToken", {
            permission: "user",
            userId: "IU2H22oihj9112221",
            roomName: roomTokenInput.value,
          })
          .then(async function (response) {
            console.log(response.data);
            if (response.data.indexOf(" ") !== -1) {
              response.data = response.data.replace(/\s*/g, " ");
            }
            try {
              client.on("user-published", handleUserPublished);
              client.on("user-unpublished", handleUserUnPublished);
              await client.join(response.data);

              localTracks = await QNRTC.createMicrophoneAndCameraTracks();

              for (const track of localTracks) {
                if (track.isVideo()) {
                  playUserTracks([track]);
                }
              }
              await client.publish(localTracks);

              joinRoomBtn.disabled = true;
              leaveRoomBtn.disabled = false;
            } catch (e) {
              alert(e.message, "warning");
            }
          });
      };

      leaveRoomBtn.onclick = (e) => {
        e.preventDefault();
        client
          .leave()
          .then(() => {
            for (const track of localTracks) {
              track.destroy();
            }
            localTracks = [];
            mediaContainer.innerHTML = "";
            joinRoomBtn.disabled = false;
            leaveRoomBtn.disabled = true;
          })
          .catch((e) => {
            alert(e.message, "warning");
          });
      };
    </script>
  </body>
</html>
